package com.guslegend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guslegend.component.MailService;
import com.guslegend.enums.BizCodeEnum;
import com.guslegend.enums.SendCodeEnum;
import com.guslegend.interceptor.LoginInterceptor;
import com.guslegend.mapper.UserMapper;
import com.guslegend.model.LoginUser;
import com.guslegend.model.UserDO;
import com.guslegend.request.UserLoginRequest;
import com.guslegend.request.UserRegisterRequest;
import com.guslegend.service.NotifyService;
import com.guslegend.service.UserService;
import com.guslegend.util.CommonUtil;
import com.guslegend.util.JWTUtil;
import com.guslegend.util.JsonData;
import com.guslegend.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author: guslegend
 * @description: 用户服务
 * @create: 2025-05-28 08:09
 **/
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private NotifyService notifyService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * * 邮箱验证码验证
     * * 密码加密（TODO）
     * * 账号唯一性检查(TODO)
     * * 插入数据库
     * * 新注册用户福利发放(TODO)
     * @param userRegisterRequest
     * @return
     */
    @Override
    public JsonData register(UserRegisterRequest userRegisterRequest) {

        if (StringUtils.isNotBlank(userRegisterRequest.getMail())) {
            //        邮箱验证码验证
            if (notifyService.checkCode(SendCodeEnum.USER_REGISTRY, userRegisterRequest.getMail(), userRegisterRequest.getCode())) {
//                创建user对象
                UserDO userDO = new UserDO();
                BeanUtils.copyProperties(userRegisterRequest, userDO);
//                设置密码
//                生成个人密钥 盐
                userDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
                String cryptPwd = Md5Crypt.md5Crypt(userDO.getPwd().getBytes(StandardCharsets.UTF_8), userDO.getSecret());
                userDO.setPwd(cryptPwd);
//                检查账号唯一性
                if (checkUniqueUser(userDO)) {
                    //                存入数据库
                    int rows = userMapper.insert(userDO);
                    log.info("用户注册： {}", userDO.toString());
//                发放优惠券 TODO
                    userInit(userDO);
                    return JsonData.buildSuccess("注册成功");
                } else {
                    return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);
                }

            } else {
                return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
            }
        }
        return null;
    }

    @Override
    public JsonData loginByPassword(UserLoginRequest userLoginRequest) {
        if (userLoginRequest.getMail() == null || userLoginRequest.getPwd() == null) {
            return JsonData.buildError("信息不全");
        }
        //先查询mail是否存在数据库（即该账号是否被注册）
        List<UserDO> selectList = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", userLoginRequest.getMail()));
        if (selectList.size() > 0) {
//            验证密码  密码+盐 同样的算法加密 与数据库的密码比较判断用户输入密码是否正确
            /**
             * 数据库存储的密码
             */
            UserDO userDO = selectList.get(0);
            String pwd = userDO.getPwd();
            /**
             * 盐
             */
            String secret = userDO.getSecret();
            //判断密码是否正确
            if (pwd.equals(Md5Crypt.md5Crypt(userLoginRequest.getPwd().getBytes(), secret))) {
                //  生成token
                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(userDO, loginUser);
                String token = JWTUtil.geneJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);
            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }

        } else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    @Override
    public JsonData loginByCode(UserLoginRequest userLoginRequest) {
        if (userLoginRequest.getMail() == null || userLoginRequest.getCode() == null) {
            return JsonData.buildError("信息不全");
        }
        //先查询mail是否存在数据库（即该账号是否被注册）
        List<UserDO> selectList = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", userLoginRequest.getMail()));
        if (selectList.size() > 0) {
            UserDO userDO = selectList.get(0);

            //        检查验证码是否有效
            boolean checkCode = notifyService.checkCode(SendCodeEnum.USER_LOGIN, userLoginRequest.getMail(), userLoginRequest.getCode());
            if (checkCode) {
                //  生成token
                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(userDO, loginUser);
                String token = JWTUtil.geneJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);
            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_CODE_ERROR);
            }
        } else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    @Override
    public UserVO findUserDetails() {
        LoginUser loginUser= LoginInterceptor.threadLocal.get();
        UserDO userDO=userMapper.selectById(loginUser.getId());
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(userDO,userVO);
        return userVO;
    }

    /**
     * 检查账号唯一性  TODO
     * 数据库唯一索引(建表时已经添加)
     * @param userDO
     * @return
     */
    private boolean checkUniqueUser(UserDO userDO) {
        return true;
    }

    /**
     * 初始化用户 发放福利
     * @param userDO
     */
    private void userInit(UserDO userDO) {

    }
}
